package com.orangelife.mobile.houserepair.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.houserepair.adapter.MyRepairListAdapter;
import com.orangelife.mobile.houserepair.biz.RepairBiz;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 *  *4.2版本报修和投诉合并为报事报修,保留报修相关接口
 * Created by YangWei
 * on 2015/11/18.
 */
public class MyRepairListActivity extends OrangeLifeBaseActivity {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.lvMyCom)
    PullToRefreshListView lvMyCom;
    @Bind(R.id.iv_title_right)
    ImageView ivTitleRight;

    /** 分辨是刷新还是加载更多 */
    private int flags = 1;
    /** 一页中数据的条数，初始设置为7条 */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /** 初始页，初始化为第一页 */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    private Dialog dialog;
    private MyRepairListAdapter<Map<String, Object>> adapter;
    private Handler mHandler;
    private List<Map<String, Object>> list;
    private List<Map<String, Object>> list2;
    Map<String, Object> map = new HashMap<>();

    RepairBiz repairBiz = RepairBiz.getInstance();
    @Bind(R.id.llNoComplainData)
    LinearLayout llNoComplainData;
    @Bind(R.id.tvNoComplain)
    TextView tvNoComplain;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_complain);
        ButterKnife.bind(this);

        initView();
        findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AddRepairJudgementActivity.ISFRESH) {
            pageNo = 1;
            repairBiz.getMyRepairList(map, pageSize, pageNo, new MyRepairHandler(this));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    /**
     * 初始化
     */
    private void initView() {
//        String commID = String.valueOf(sp.getComInfo().get("commID"));
//        map.put("commID", commID);
    }

    /**
     * 赋值并判断
     */
    private void findView() {
        tvNoComplain.setText("暂无报事报修");
        tvTitle.setText("报事报修");
        ivTitleRight.setBackgroundResource(R.drawable.ic_new_add);
        ivTitleRight.setVisibility(View.VISIBLE);

        mHandler = new Handler();

        getDataFromServer();
        pageNo = 1;
        repairBiz.getMyRepairList(map, pageSize, pageNo, new MyRepairHandler(this));
        setAdapter();
        lvMyCom.setPullLoadEnable(false);
        lvMyCom.setAdapter(adapter);
        pullListView();

    }

    /**
     * 设置适配器
     */
    private void setAdapter() {
        list = new ArrayList<Map<String, Object>>();
        list2 = new ArrayList<Map<String, Object>>();
        adapter = new MyRepairListAdapter<Map<String, Object>>(this, list);
        lvMyCom.setPullLoadEnable(false);
        lvMyCom.setAdapter(adapter);
    }

    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvMyCom.setXListViewListener(new PullToRefreshListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        repairBiz.getMyRepairList(map, pageSize, pageNo, new MyRepairHandler(MyRepairListActivity.this));
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        repairBiz.getMyRepairList(map, pageSize, pageNo, new MyRepairHandler(MyRepairListActivity.this));
                         onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvMyCom.stopRefresh();
        lvMyCom.stopLoadMore();
        lvMyCom.setRefreshTime(new Date().toLocaleString());
    }

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    private void updateListView(List<Map<String, Object>> list2) {

        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                if (flags == 1) {
                    llNoComplainData.setVisibility(View.VISIBLE);
                    lvMyCom.setVisibility(View.GONE);
                    list.clear();
                    lvMyCom.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();

                } else {
                    llNoComplainData.setVisibility(View.GONE);
                    lvMyCom.setVisibility(View.VISIBLE);
                    lvMyCom.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            } else {
                if (flags == 1) {
                    llNoComplainData.setVisibility(View.GONE);
                    lvMyCom.setVisibility(View.VISIBLE);
                    list.clear();
                    lvMyCom.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                } else {
                    llNoComplainData.setVisibility(View.GONE);
                    lvMyCom.setVisibility(View.VISIBLE);
                    lvMyCom.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            }
        } else {
            lvMyCom.setPullLoadEnable(false);
        }
    }

    @OnClick(R.id.llRightClick)
    public void OnClikc(View v){
//        if (HouseBiz.hasHouse()) {
            IntentHelper.getInstances().getIntent(this, AddRepairActivity.class);
//        } else {
//            Intent intent = new Intent();
//            intent.putExtra("title", "房屋报修");
//            intent.putExtra("hint", "您尚未进行身份认证，无法进行报修，请先认证身份。");
//            intent.setClass(this, ApplyCertActivity.class);
//            startActivity(intent);
//        }
        BLog.getInstance().click(BLog.PREPAIR);
    }
    static class MyRepairHandler extends Handler {
        private WeakReference<MyRepairListActivity> myRepairListActivity = null;

        public MyRepairHandler(MyRepairListActivity activity) {
            myRepairListActivity = new WeakReference<MyRepairListActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MyRepairListActivity act = myRepairListActivity.get();
            if (act != null) {
                switch (msg.what) {
                    case 1:
                        act.list2 = JsonReponseHandler.getListFromJson(
                                String.valueOf(msg.obj), act.adapter, act.dialog);
                        act.updateListView(act.list2);
                        break;
                    case 500:
                        DialogHelper.closeDialog(act.dialog);
                        ToastHelper.getInstance()._toast(
                                msg.obj.toString());
                        break;
                    case 1011:
                        act.isLogin(act.dialog);
                        break;
                    default:
                        break;
                }
            }
        }

    }


}
